<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px;"
        >
            <el-breadcrumb-item :to="{ path: '/query/IntegratedQuery' }">
                <i class="el-icon-search"></i>综合查询
            </el-breadcrumb-item>
            <el-breadcrumb-item>标注</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="main-container">
            <div class="header-control">
                <el-checkbox
                    style="margin-right:30px;"
                    :indeterminate="isIndeterminate"
                    v-model="checkAll"
                    @change="handleCheckAllChange"
                >全选</el-checkbox>
                <el-upload
                    class="upload-demo"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    :on-success="onSuccess"
                    multiple
                    :on-exceed="handleExceed"
                >
                    <!-- <el-button size="small" type="primary">导入</el-button> -->
                    <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>
                <el-button
                    size="small"
                    type="primary"
                    @click="exportPic"
                >导出</el-button>
            </div>
            <div class="image-container">
                <el-checkbox-group
                    v-model="checkedPics"
                    @change="handleCheckedPicsChange"
                >
                    <el-checkbox
                        v-for="pic in pics"
                        :label="pic.image_url"
                        :key="pic.image_url"
                    >
                        <img
                            :src="imageServiceURL+pic.image_url"
                            style="width:150px;height:150px;"
                            id='Img'
                        />
                        <div>标题:{{pic.remark_one}}</div>
                        <div>标注内容:{{pic.remark_two}}</div>
                    </el-checkbox>
                </el-checkbox-group>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'DiagnosisBiopsyMark',
    data() {
        return {
            imageServiceURL: process.env.ImageServiceURL,
            checkAll: false,
            checkedPics: [],
            isIndeterminate: true,
            pics: [],
            bindPics: [],
            patientName: '',
            PathologyId: '',
        };
    },
    mounted() {
        const { state } = this.$store;
        const { pathologyId } = state.diagnosis;
        this.$axios({
            method: 'GET',
            url: '/PROXY-Remote/annotations/all-annotations',
            params: {
                pathologyId: pathologyId,
            },
        }).then((res) => {
            // 请求失败
            if (res.data.code !== 200) {
                throw new Error(res.data);
            } else {
                this.pics = res.data.data;
                this.pics.forEach((item) => {
                    this.bindPics.push(item.image_url);
                });
                this.patientName = res.data.data[0].name;
                this.PathologyId = pathologyId;
            }
        });
    },
    methods: {
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        beforeUpload(file) {
            console.log('file', file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 3 个文件，本次选择了 ${
                    files.length
                } 个文件，共选择了 ${files.length + fileList.length} 个文件`
            );
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        onSuccess(response, file, fileList) {
            this.$message.success('导入成功');
        },
        //点击全选
        handleCheckAllChange(val) {
            this.checkedPics = val ? this.bindPics : [];
            this.isIndeterminate = false;
            console.log(val);
        },
        //点击选择单个图片
        handleCheckedPicsChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.pics.length;
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.pics.length;
        },
        //导出数据为txt的方法
        exportRaw(name, data) {
            var urlObject = window.URL || window.webkitURL || window;
            var exportBlob = new Blob([data]);
            var saveLink = document.createElement('a');
            saveLink.href = urlObject.createObjectURL(exportBlob);
            saveLink.download = name;
            this.fakeClick(saveLink);
        },
        fakeClick(obj) {
            var ev = document.createEvent('MouseEvents');
            ev.initMouseEvent(
                'click',
                true,
                false,
                window,
                0,
                0,
                0,
                0,
                0,
                false,
                false,
                false,
                false,
                0,
                null
            );
            obj.dispatchEvent(ev);
        },

        //导出图片
        exportPic() {
            if (this.checkedPics.length == 0) {
                this.$message.warning('请选择需要导出的切片');
            } else {
                this.checkedPics.forEach((item) => {
                    let url = this.imageServiceURL + item;
                    let row = this.patientName + this.PathologyId;
                    let fType = 'png';
                    this.download(url, row, fType);
                    // let alink = document.createElement("a");
                    // alink.download = this.patientName+this.PathologyId;
                    // alink.href = this.imageServiceURL + item;
                    // alink.style.display = "none";
                    // document.body.appendChild(alink);
                    // alink.click();
                    // document.body.removeChild(alink);
                    //创建标注txt文档
                    this.pics.forEach((it) => {
                        let filePic = item.split('/');
                        let fileNa = filePic[3].split('.');
                        console.log(fileNa[0]);
                        if (it.image_url == item) {
                            let text =
                                '标题:' +
                                it.remark_one +
                                ';' +
                                '提示内容:' +
                                it.remark_two;
                            let name = it.name + this.PathologyId + fileNa[0]; // 命名
                            this.exportRaw(name, text);
                        }
                    });
                });
            }
        },

        download(src, row, fType) {
            //row.ITEMNAME为文件名称，src为文件存储地址            　　　　　　　　if (this.isImageInChromeNotEdge(fType)) {//判断是否为chrome里的图片
            if (this.isImageInChromeNotEdge(fType)) {
                //判断是否为chrome里的图片
                this.ImgtodataURL(src, row, fType);
            } else {
                this.downloadNormalFile(src, row);
            }
        },
        isImageInChromeNotEdge(fType) {
            let bool = false;
            if (
                window.navigator.userAgent.indexOf('Chrome') !== -1 &&
                window.navigator.userAgent.indexOf('Edge') === -1
            )
                (fType === 'jpg' ||
                    fType === 'gif' ||
                    fType === 'png' ||
                    fType === 'bmp' ||
                    fType === 'jpeg' ||
                    fType === 'svg') &&
                    (bool = true);
            return bool;
        },
        downloadNormalFile(src, filename) {
            var link = document.createElement('a');
            link.setAttribute('download', filename);
            link.href = src;
            document.body.appendChild(link); //添加到页面中，为兼容Firefox浏览器
            link.click();
            document.body.removeChild(link); //从页面移除
        },
        ImgtodataURL(url, filename, fileType) {
            this.getBase64(url, fileType, (_baseUrl) => {
                // 创建隐藏的可下载链接
                var eleLink = document.createElement('a');
                eleLink.download = filename;
                eleLink.style.display = 'none';
                // 图片转base64地址
                eleLink.href = _baseUrl;
                // 触发点击
                document.body.appendChild(eleLink);
                eleLink.click();
                // 然后移除
                document.body.removeChild(eleLink);
            });
        },
        getBase64(url, fileType, callback) {
            //通过构造函数来创建的 img 实例，在赋予 src 值后就会立刻下载图片
            var Img = new Image(),
                dataURL = '';
            Img.src = url;
            Img.setAttribute('crossOrigin', 'Anonymous');
            Img.onload = function () {
                //要先确保图片完整获取到，这是个异步事件
                var canvas = document.createElement('canvas'), //创建canvas元素
                    width = Img.width, //确保canvas的尺寸和图片一样
                    height = Img.height;
                canvas.width = width;
                canvas.height = height;
                canvas.getContext('2d').drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
                dataURL = canvas.toDataURL('image/' + fileType); //转换图片为dataURL
                callback ? callback(dataURL) : null;
            };
        },
    },
};
</script>

<style>
.header-control {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 20px;
}
.image-container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
.image-container .el-checkbox .el-checkbox__input {
    vertical-align: top;
}
</style>
